package com.asia5b.a5mall.middleware.config

import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import com.asia5b.a5mall.middleware.event.DownloadApkEvent
import com.asia5b.a5mall.middleware.utils.UriUtil
import com.asia5b.a5mall.middleware.utils.dddLog
import com.asia5b.a5mall.middleware.utils.getEventBus
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.RandomAccessFile
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection

/**
 * Created by zhangyuncai on 2020/6/8.
 */
class UpdateIntentService : IntentService("UpdateIntentService") {
    var downloadUrl = ""//apk下载地址
    var downloadApkFilePath = ""//apk储存地址
    var newBuild = ""//最新的apk的build号

    companion object {
        var isRunning = false
        val CONNECT_TIMEOUT = 15 * 1000
        fun startUpdateIntentService(context: Context, downloadUrl: String, build: String) {
            val intent = Intent(context, UpdateIntentService::class.java)
            intent.putExtra("downloadUrl", downloadUrl)
            intent.putExtra("newBuild", build)
            context.startService(intent)
        }

        /**
         * 安装apk
         */
        fun installApk(context: Context, filePath: String) {
            try {
                val file = File(filePath)
                val intent = Intent(Intent.ACTION_VIEW)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                //适配7.0以上
                val uri = UriUtil.getUri(context, file)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    intent.setDataAndType(uri, "application/vnd.android.package-archive")
                } else {
                    intent.setDataAndType(
                            uri,
                            "application/vnd.android.package-archive")
                }
                context.startActivity(intent)
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }

        }
    }

    override fun onHandleIntent(intent: Intent?) {
        downloadUrl = intent!!.getStringExtra("downloadUrl")!!
        newBuild = intent!!.getStringExtra("newBuild")!!
        downloadApkFilePath = getExternalCacheDir()!!.getPath() + "/" + newBuild + ".apk"
        if (!TextUtils.isEmpty(downloadUrl) && !isRunning) {
            isRunning = true
            start()
            makeRequest()
        }
    }


    /**
     * 创建请求
     */
    fun makeRequest() {
        var apkFileSize = 0L
        var inputStream: InputStream? = null
        var randomAccessFile: RandomAccessFile? = null
        var connection: HttpURLConnection? = null



        try {

            val url = URL(downloadUrl)
            if (downloadUrl.startsWith("https")) {
                connection = url.openConnection() as HttpsURLConnection
            } else {
                connection = url.openConnection() as HttpURLConnection
            }
            connection.requestMethod = "GET"
            connection.readTimeout = CONNECT_TIMEOUT
            connection.connectTimeout = CONNECT_TIMEOUT
            connection.connect()
            inputStream = connection.inputStream
            apkFileSize = connection.contentLength.toLong()

            randomAccessFile = RandomAccessFile(downloadApkFilePath, "rwd")
            val buffer = ByteArray(1024 * 4)

            //apk文件长度
            var length = 0
            //已下载百分比进度条
            var oldProgress = 0
            //已完成长度
            var completeFileSize: Long = 0

            while (true) {
                length = inputStream.read(buffer)
                if (length == -1) {
                    break
                }

                randomAccessFile.write(buffer, 0, length)
                completeFileSize += length.toLong()

                val progress = (completeFileSize * 100 / apkFileSize).toInt()
                if (oldProgress != progress) {
                    oldProgress = progress

                    if (oldProgress % 5 == 0) {
                        progress(oldProgress)
                    }
                }
            }

            if (oldProgress < 100) {
                fail()
            } else {
                finish()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            fail()
        } finally {

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (e: IOException) {
                    e.printStackTrace();
                }
            }

            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (e: IOException) {
                    e.printStackTrace();
                }
            }

            if (connection != null) {
                connection.disconnect();
            }

        }
    }

    /**
     * 开始
     */
    fun start() {
        dddLog("start")
    }

    /**
     * 进度条
     */
    fun progress(progress: Int) {
        getEventBus().post(DownloadApkEvent(progress))
        dddLog("progress:$progress")
    }

    /**
     * 错误
     */
    fun fail() {
        dddLog("fail")
    }

    /**
     * 完成
     */
    fun finish() {
        dddLog("finish")
        getEventBus().post(DownloadApkEvent(100, downloadApkFilePath))
    }


    override fun onDestroy() {
        isRunning = false
        super.onDestroy()
    }
}